package com.imooc.controller;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.imooc.domain.User;
import com.imooc.redis.RedisService;
import com.imooc.redis.UserKey;
import com.imooc.result.CodeMsg;
import com.imooc.result.Result;
import com.imooc.service.UserService;

@RestController
@RequestMapping("/demo")
public class DemoController {
	
	@Autowired
	UserService userService;
	
	@Autowired
	RedisService redisService;
	
	/**
	 * redis
	 * @return
	 */
	
	@RequestMapping("/redis/set")
	public Result<Boolean> redisSet(){
		User user1 = new User();
		
		user1.setId(10002);
		user1.setName("albin");
		boolean b = false;
		if(!redisService.exsits(UserKey.GETBYNAME, ""+1)){
			b = redisService.set(UserKey.GETBYNAME, ""+1, user1);
		}else{
			//Long l = redisService.incr(UserKey.GETBYID, ""+1);
			b = redisService.set(UserKey.GETBYNAME, ""+2, user1);
		}
		
		//User u = redisService.get("json:user", User.class);
		return Result.success(b);
	}
	
	@RequestMapping("/redis/get")
	public Result<User> redisGet(){
		User u = redisService.get(UserKey.GETBYNAME, ""+1, User.class);
		return Result.success(u);
	}
	
	
	@RequestMapping("/tx")
	public Result<Boolean> tx(){
		userService.insertUser();
		
		return Result.success(true);
	}
	
	@RequestMapping("/user/{id}")
	public Result<User> get(@PathVariable("id") Integer id){
		System.out.println("id:"+id);
		User user = userService.getById(id);
		System.out.println("==user="+user.getName());
		return Result.success(user);
	}
	

	@RequestMapping("/test")
	public Result<String> demo(){
		return Result.success("hello world");
	}
	
	@RequestMapping("/error")
	public Result<String> error(){
		return Result.error(CodeMsg.SERVER_ERROR);
	}
	
	@RequestMapping("/thym")
	public String thym(Model model){
		model.addAttribute("name", "Bobe Bryant");
		return "hello";
	}
	
	
	
}
